package com.dyg.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class LoginController {
	
	
	
	@RequestMapping(value = "login",method = RequestMethod.GET)
	public String jumpLogin(){
		return "login";
	}
	
	
	/**
	 * 实际的登录代码
	 * 如果登录成功，跳转至首页；登录失败，则将失败信息反馈对用户
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.POST )
	public String doLogin(HttpServletRequest request, Model model) {
		String msg = null;
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.out.println(userName);
		System.out.println(password);
		
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		token.setRememberMe(true);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			/*if (subject.isAuthenticated()) {
				return "index";
			} else {
				return "login";
			}*/
		} catch (UnknownAccountException e) {
            e.printStackTrace();
            msg = e.getMessage();
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            msg = "密码不匹配(生产环境中应该写:用户名和密码的组合不正确)";
        } catch (LockedAccountException e){
            e.printStackTrace();
            msg = e.getMessage();
        }
        if(msg == null){
            return "redirect:/admin/user/list";
        }

        model.addAttribute("msg",msg);
        return "login";
	}
	
	@RequestMapping(value = "/logout",method = RequestMethod.GET)
	public String logout(Model model){
		
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		model.addAttribute("msg","退出成功");
		return "login";
	}

	 @RequestMapping(value = "/unAuthorization")
	    public String unAuthorization(){
	        return "unAuthorization";
	    }
}
